import urllib.parse
import copy
import json
import requests
import random
from impl._baidu_misc import _get_valid_json, _parse_baidu_json


class BaiduImageJsonAPICrawler:
    def __init__(self, search_word: str, request_session, header_config, connection_timeout, verbose):
        api_header = copy.copy(header_config['API_HEADER']['template'])
        user_agent = header_config['API_HEADER']['User-Agent']
        api_header['User-Agent'] = random.choice(user_agent)
        url_search_name = urllib.parse.quote(search_word)
        search_url = f'https://image.baidu.com/search/index?tn=baiduimage&word={url_search_name}'
        api_header['Referer'] = search_url
        self.url_search_name = url_search_name
        self.request_session = request_session
        self.api_header = api_header
        self.connection_timeout = connection_timeout
        self.batch_size = 30
        self.batch_index = 0
        self.verbose = verbose
        self.no_next = False

    def get_next(self):
        if self.no_next:
            return None
        api_url = f'https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord={self.url_search_name}&cl=&lm=&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&hd=&latest=&copyright=&word={self.url_search_name}&s=&se=&tab=&width=&height=&face=&istype=&qc=&nc=&fr=&expermode=&nojc=&pn={self.batch_index * self.batch_size}&rn={self.batch_size}&gsm=3c&1628165200301='
        self.batch_index += 1
        try:
            # r = session.get(search_url, headers=downloader_config['BAIDU_SITE_HEADER'], timeout=connection_timeout)
            # r.raise_for_status()
            r = self.request_session.get(api_url, headers=self.api_header, timeout=self.connection_timeout)
            r.raise_for_status()
            json_bytes = _get_valid_json(r.content)
        except requests.RequestException as e:
            if self.verbose:
                print(f'{api_url} {e}')
            return None
        response_json = json.loads(json_bytes, strict=False)
        if 'antiFlag' in response_json:
            string = 'Being treated as bot. '
            if 'message' in response_json:
                string += f"message: {response_json['message']}"
            print(string)
            return None
        parsed = _parse_baidu_json(response_json)
        if parsed is None or len(parsed) < self.batch_size:
            self.no_next = True

        return parsed
